package com.weixin.servlet.backstage;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.weixin.service.ILoginService;
import com.weixin.service.impl.LoginServiceImpl;
import com.weixin.vo.Admin;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    ILoginService loginService = new LoginServiceImpl();
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		String code = null;
		if(request.getParameter("code")!=null&&!(request.getParameter("code").equals(""))) {
			code = request.getParameter("code");
		}
		HttpSession session = request.getSession();
		String cod = (String)session.getAttribute("code");
		
		String admin_account = null;
		if(request.getParameter("name")!=null&&!(request.getParameter("name").equals(""))) {
			admin_account = request.getParameter("name");
		}
		String admin_pwd = null;
		if(request.getParameter("password")!=null&&!(request.getParameter("password").equals(""))) {
			admin_pwd = request.getParameter("password");
		}
		Admin admin = null;
		try {
			//调用业务层的方法查找数据库中的信息
		    admin = loginService.selectAdmin(admin_account, admin_pwd);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		boolean b = code.equals(cod);
		if(!b&&admin!=null) {
			response.getWriter().println(1);//验证码错误
		}else if(b&&admin==null) {
			response.getWriter().println(2);//账号或密码错误
		}else if(b&&admin!=null) {
			request.getSession().setAttribute("admin", admin);//登陆成功
			response.getWriter().println(3);
		}else if(!b&&admin==null) {
			response.getWriter().println(0);//登陆失败
		}
		
	}

}
